<?php

namespace app\api\controller\sync;

use app\api\controller\Base;
use app\api\controller\mytool\Sendmessage;
use app\common\model\orderhawa\HawaList;
use app\common\model\Sync\SyncCenter;
use app\common\model\power\Rolepower;
use app\common\model\user\User as UserModel;
use app\api\controller\Pub;

/**
 * 同步中心主方法
 */
class Sync extends Base
{

    /**
     * 产生jwt加密串，参考session
     */
    public function initialize()
    {
        parent::initialize();
        self::is_login();
        Rolepower::powerguard(206001);
    }

    /**
     * 指令列表
     * @return [type] [description]
     */
    function list() {
        $data = input('get.');
        $data['Type'] = 'SyncCenter';
        $data = init_where($data, ['state' => 'Status']);
        $list = SyncCenter::usergetlist($data);
        foreach ($list['list'] as $key => $value) {
            if (empty($value['userInfo']['Name'])) {
                $list['list'][$key]['Name'] = '暂无';
            } else {
                $list['list'][$key]['Name'] = $value['userInfo']['Name'];
            }
        }
        $list['tr']['title'] = ['指令类型', '创建时间', '指令状态', '查看', '处理人'];
        $list['tr']['key']   = ['Type', 'CreateTime', 'Status', 'Id', 'Name'];
        return myok($list);
    }

    /**
     * 查看指令详情
     * @return [type] [description]
     */
    public function getinfo()
    {
        $param = $this->request->get();
        $info  = SyncCenter::where('Id', $param['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            return myerr('非法请求');
        }
        switch ($info['Type']) {
            case '社会源收集申报':
            case '社会源收集申报（保存模块）':
            case '社会源收集申报（手动确认模块）':
            case '社会源收集申报（自动确认模块）':
                //显示视图
                $info['view'] = Synccreate::ssysb_view($info['ListId']);
                //关联信息
                $info['relation'] = HawaList::sync_relation_ssysb($info['ListId']);
                break;
               
        }
        return myok($info);
    }

    /**
     * 审核 & 修改指令 并将指令发送出去
     * Status 2:拒绝 1通过
     * @return [type] [description]
     */
    public function review()
    {
        $param = $this->request->post();
        if (empty($param['id']) || empty($param['Status'])) {
            return myerr('非法请求');
        }
        //运行指令
        $run = self::runcode($param);
        if(!$run['code']){return myerr($run['msg']);}
        $sb = SyncCenter::whereOr('Status','in',[Synccenter::STATEINT,Synccenter::STATERETURNWAIT])->find();
        if(empty($sb)){
            return myok('empty');
        }else{
            return myok($sb->Id);
        }
    }

    /**
     * 运行指令
     * @param  [type] $param [description]
     * @return [type]        [description]
     */
    public function runcode($param){
        $sync = SyncCenter::where('Id', $param['id'])->findOrEmpty();
        if (empty($sync)) {
            return serr('非法请求');
        }
        // 解析同步内容
        if(!empty($param['SyncContent'])){
            $param['SyncContent'] = json_array($param['SyncContent'],true);
        }  
        //修改审核状态以及操作人
        $sync->UpUserId = Pub::userid();
        if ($param['Status'] == 2) {
            //取消执行此命令
            $sync->Status = SyncCenter::STATECANCEL;
            //将数据格式化后保存
            if(!empty($param['SyncContent'])){
                $sync->SyncContent = json_encode($param['SyncContent']);
            }
        } else {
            $sync->Status = SyncCenter::STATESTART;

            //同步中心执行的账号和密码
            $sb = Synccenter::getpassword(GOVUSERNAME, GOVPASSWORD);
            if (!$sb['code']) {
                return serr($sb['msg']);
            }
            $param['SyncContent']['username'] = GOVUSERNAME;//账号
            $param['SyncContent']['password'] = $sb['msg'];//密码
            $param['SyncContent']['COMPANYCITY'] = COMPANYCITY;//所属城市

            //数据格式化
            if(!empty($param['SyncContent'])){
                $sync->SyncContent = json_encode($param['SyncContent']);
            }
            // 执行同步
            $data = $sync;
            $data['XwcId'] = $param['id'];
            $sb  = SyncCenter::syncapi('index/createcode', $data);
            if (!$sb['code']) {
                //执行失败
                return serr('同步中心:'.$sb['msg']);
            }
        }
        //存储修改数据
        $sync->SyncTime = date('Y-m-d H:i:s',time());
        $sync->save();
        return sok();
    }

    /**
     * 手动创建指令
     * @return [type] [description]
     */
    public function create_code(){
        $data = input('get.');
        if(empty($data['type'])){
            return myerr('缺少数据');
        }
        switch ($data['type']) {
            //社会源收集申报（手动确认模块）
            case 'ssysb_create_get_data':
                return self::ssysb_create_get_data($data);
                break;
            default:
                return myerr('类型错误');
        }
    }
    /**
     * 社会源收集申报（手动确认模块）
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function ssysb_create_get_data($data){
        if(empty($data['id'])){
            return myerr('缺少数据');
        }
        //创建同步指令
        $data = Synccreate::ssysb_create_get_data($data['id']);
        if(!$data['code']){
            return myerr($data['msg']);
        }
        $data = $data['msg'];
        //执行同步指令
        $sb = self::runcode($data);
        if(!$sb['code']){
            return myerr($sb['msg']);
        }else{
            return myok('操作成功');
        }
    }

    /**
     * 判断账号是否登录
     * @return boolean [description]
     */
    private function is_login()
    {
        $data = UserModel::is_sessionlogin();
        if (!$data['code']) {
            $data['options'] = 'relogin';
            json($data)->send();
            exit;
        }
    }

}
